﻿using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

namespace Infrastructure.Model
{
    /// <summary>
    /// 服务中心选项
    /// </summary>
    public class ServiceCenterOption
    {
        /// <summary>
        /// 本地IP
        /// </summary>
        private string _localIp;
        /// <summary>
        /// consul地址 构建和管理现代分布式系统
        /// </summary>
        public string ConsulUrl { get; set; }
        /// <summary>
        /// Zipkin 分布式跟踪 跟踪和监控微服务架构中的请求流。
        /// </summary>
        public string ZipkinUrl { get; set; }
        /// <summary>
        /// 服务名
        /// </summary>
        public string ServiceName { get; set; }
        /// <summary>
        /// 服务客户端地址
        /// </summary>
        public string ServiceCenterUrl { get; set; }
        /// <summary>
        /// 访问令牌
        /// </summary>
        public string AccessToken { get; set; }
        /// <summary>
        /// Consul分布式微服务集群地址
        /// </summary>
        public string GetConsulUrl { get; set; } = "api/Center/GetConsulAddress";
        /// <summary>
        /// Zipkin 分布式跟踪 跟踪和监控微服务架构
        /// </summary>

        public string GetZipkinUrl { get; set; } = "api/Center/GetZipkinAddress";


        public string LocalIP
        {
            get
            {
                return _localIp ?? GetLocalIP();
            }
            set
            {
                _localIp = value;
            }
        }
        /// <summary>
        /// 本地端口
        /// </summary>
        public int LocalPort { get; set; } = 5000;
        /// <summary>
        /// 健康检查地址
        /// </summary>

        public string HealthCheckUrl { get; set; } = "api/HealthCheck/Index";


        public Dictionary<string, string> ConstService { get; set; }
        /// <summary>
        /// 获取本地IP
        /// </summary>
        /// <returns></returns>
        private static string GetLocalIP()
        {
            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
                .Where(p => p.OperationalStatus == OperationalStatus.Up &&
                            p.NetworkInterfaceType != NetworkInterfaceType.Loopback &&
                            p.SupportsMulticast)
                .SelectMany(p => p.GetIPProperties().UnicastAddresses)
                .Where(p => p.Address.AddressFamily == AddressFamily.InterNetwork &&
                            !IPAddress.IsLoopback(p.Address))
                .OrderByDescending(p => int.Parse(p.Address.ToString().Split('.')[3])); // 按IP地址的最后一段数字降序排序

            return networkInterfaces.FirstOrDefault()?.Address.ToString();
        }
    }
}
